import 'dart:async';

import 'package:cunyutech_flutter_ui/src/theme/main.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class LoadingDotPointer extends CustomPainter {
  final double radius;
  final double spacing;
  final Color activeColor;
  final Color color;
  final int count;
  final int activeIndex;
  
  LoadingDotPointer({
    this.activeColor, 
    this.color, 
    this.count = 3, 
    this.activeIndex = 0,
    this.radius = 6,
    this.spacing = 10
  });

  @override
  void paint(Canvas canvas, Size size) {
    Offset offset = Offset(0, radius);
    for(int i=0;i<count;i++) {
      final Color paintColor = activeIndex == i ? activeColor : color;
      final double x = offset.dx + radius;
      final offsetCenter = Offset(x, offset.dy);
      final paint = Paint()
          ..style = PaintingStyle.fill
          ..color = paintColor;
      canvas.drawCircle(offsetCenter, radius, paint);
      offset += Offset(radius+spacing, 0);
    }
  }
  
  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}

class LoadingDot extends StatefulWidget {
  LoadingDot({Key key, this.count = 3, this.radius = 6, this.spacing = 10}) : super(key: key);

  final int count;
  final double radius;
  final double spacing;

  @override
  _LoadingDotState createState() => _LoadingDotState();
}

class _LoadingDotState extends State<LoadingDot> {

  int activeIndex = 0;
  Timer timer;
  @override
  void initState() {
    timer = Timer.periodic(Duration(milliseconds: 500), (Timer _timer){
      if(timer == null || !timer.isActive) {
        if(_timer != null) {
          _timer.cancel();
          _timer = null;
        }
      }
      setState(() {
        activeIndex = (activeIndex + 1) % widget.count;
      });
    }); 
    super.initState();
  }

  @override
  void dispose() { 
    if(timer != null) {
      timer.cancel();
      timer = null;
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final double width = widget.count * widget.radius * 2 + (widget.count - 1)*widget.spacing;
    final double height = widget.radius * 2;
    var cs = CYThemeData.of(context);
    return Container(
      width: width,
      height: height,
      child: CustomPaint(
        painter: LoadingDotPointer(
          count: widget.count,
          radius: widget.radius,
          spacing: widget.spacing,
          activeIndex: activeIndex,
          activeColor: cs.primaryForeColor,
          color: cs.foreColorSystem.secondaryColor
        )
      ),
    );
  }
}